<?
    final class TypesController extends PrincipioLab_Controller_Action
    {
        const ACTION_VIEW = 0;
        const ACTION_ADD = 1;
        const ACTION_EDIT = 2;
        const ACTION_CUSTOMIZE = 3;
        const ACTION_TFTP = 4;
        const ACTION_SHORT = 5;


        private function setActionViewData($action)
        {
            switch ($action)
            {
                case self::ACTION_ADD:
                    Principio_Common::setButtons(
                        "Add type",
                        "ajaxTypes({id: -1, action: 'add', use_inner: true});",
                        "addItem({menu: 'types', container: 'inner'});"
                    );
                    break;

                case self::ACTION_EDIT:
                    $model_action_menu = new Principio_Model_ActionMenu();
                    $model_action_menu->setJsAjaxFunction("Types")->setItemID($this->view->model_type->getID())->
                        setMenu(Principio_Model_MenuItem::fromArray(['Edit' => "edit", 'TFTP' => "tftp", 'Custom templates' => "customize", 'Delete' => "delete"]));

                    $this->view->model_action_menu = $model_action_menu;

                    Principio_Common::setButtons(
                        "Apply",
                        "ajaxTypes({action: 'edit', id: ".$this->view->model_type->getID()."});",
                        "ajaxTypes({id: ".$this->view->model_type->getID().", action: 'edit', no_apply: true});"
                    );
                    break;

                case self::ACTION_CUSTOMIZE:
                    Principio_Common::setButtons(
                        "Apply",
                        "ajaxTypes({id: ".$this->view->model_type->getID().", action: 'customize', exts_count: ".$this->view->model_type->getExts().", no_refresh: true});",
                        "ajaxTypes({id: ".$this->view->model_type->getID().", action: 'customize', no_apply: true});"
                    );
                    break;

                case self::ACTION_TFTP:
                    Principio_Common::setButtons(
                        "Apply",
                        "ajaxTypes({id: ".$this->view->model_type->getID().", action: 'tftp', no_refresh: true});",
                        "ajaxTypes({id: ".$this->view->model_type->getID().", action: 'tftp', no_apply: true});"
                    );
                    break;

                case self::ACTION_SHORT:
                    Principio_Common::setButtons(
                        "Apply",
                        "ajaxTypes({id: ".$this->view->model_type_in_company->getModelType()->getID().", company_id: "
                            .$this->view->model_type_in_company->getModelCompany()->getID()
                            .", action: 'short', use_inner: true, exts_count: "
                            .$this->view->model_type_in_company->getModelType()->getExts()
                            .", no_refresh: true});",

                        "ajaxTypes({id: ".$this->view->model_type_in_company->getModelType()->getID().", company_id: "
                            .$this->view->model_type_in_company->getModelCompany()->getID()
                            .", action: 'short', use_inner: true, no_apply: true});"
                    );
                    break;

            };
        }


        public function indexAction()
        {
            $this->view->title = "SPA types";
        }
               
        
        private function validate()
        {
            if ($this->checkPostItemString("tftp_filename", "TFTP Filename"))
                $this->view->model_type->setTFTPFilename($this->post_data['tftp_filename']);

            if ($this->checkPostItemString("caption", "Caption"))
                $this->view->model_type->setCaption($this->post_data['caption']);

            if ($this->checkPostItem("firmware_id", "Firmware ID"))
                $this->view->model_type->setModelFirmware(Principio_Model_FirmwareMapper::get(intval($this->post_data['firmware_id'])));

            if (!Principio_Common::$is_error)
            {
                Principio_Common::checkValidity(Principio_Model_TypeMapper::checkUniqueTFTPFilename($this->view->model_type), "SPA Type with TFTP filename [".$this->view->model_type->getTFTPFilename()."] already exists.");
                Principio_Common::checkValidity(Principio_Model_TypeMapper::checkUniqueCaption($this->view->model_type), "SPA Type with caption [".$this->view->model_type->getCaption()."] already exists.");
            };

            return !Principio_Common::$is_error;
        }


        public function shortAction()
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "Type ID")) && ($this->checkPostItemInt("company_id", "Company ID")))
            {
                $this->view->model_type_in_company = Principio_Model_Company_AbstractMapper::fetch($this->post_data['company_id'])
                    ->getModelTypeInCompany(Principio_Model_TypeMapper::fetch($this->post_data['id']));

                if ($this->is_apply)
                {
                    for ($i = 0; $i <= $this->view->model_type_in_company->getModelType()->getExts() + 1; $i++)
                    {
                        if (!isset($this->post_data["ext".$i."_template"]))
                            $this->view->model_type_in_company->setTemplate($i - Principio_Model_Templatable::TEMPLATE_SHIFT, "");
                        else
                            $this->view->model_type_in_company->setTemplate($i - Principio_Model_Templatable::TEMPLATE_SHIFT, $this->post_data["ext".$i."_template"]);
                    };

                    if ($this->view->model_type_in_company->save())
                        Principio_Common::reportMessage("Templates were updated.");
                };

                $this->view->title = "Overview of type [".$this->view->model_type_in_company->getModelType()->getCaption()."] in "
                    .($this->view->model_type_in_company->getModelCompany()->isPool() ? "pool" : "company")
                    ." [".$this->view->model_type_in_company->getModelCompany()->getCaption()."]";
                $this->setActionViewData(self::ACTION_SHORT);
            };
        }


        public function viewAction()
        {
            return $this->editAction(self::ACTION_VIEW);
        }
	
	
        public function editAction($action = self::ACTION_EDIT)
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "Type ID")))
            {
                $this->view->firmwares = Principio_Model_FirmwareMapper::get();
                $this->view->is_add = false;
                $this->view->action = ($action == self::ACTION_EDIT) ? "edit" : "view";
                $this->view->model_type = Principio_Model_TypeMapper::fetch($this->post_data['id']);
                $model_type_old = clone $this->view->model_type;

                if (($this->is_apply) && ($this->validate()))
                {
                    if ($model_type_old->getTFTPFilename() != $this->view->model_type->getTFTPFilename())
                    {
                        $tftp_filename_new = Principio_Model_SettingMapper::fetch(Principio_Model_SettingMapper::SETTING_TFTP_PATH_TO_INITIAL_CONFIGS)->getValue()."/".$this->view->model_type->getTFTPFilename();
                        $tftp_filename_old = Principio_Model_SettingMapper::fetch(Principio_Model_SettingMapper::SETTING_TFTP_PATH_TO_INITIAL_CONFIGS)->getValue()."/".$model_type_old->getTFTPFilename();

                        if (Principio_Common::checkValidity(
                            @rename($tftp_filename_old, $tftp_filename_new),
                            "Can't move TFTP config from [".$tftp_filename_old."] to [".$tftp_filename_new."]."
                        ))
                            Principio_Common::reportMessage("TFTP config was moved from [".$tftp_filename_old."] to [".$tftp_filename_new."].");

                    };

                    if (!Principio_Common::$is_error)
                    {
                        if ($this->view->model_type->save())
                            Principio_Common::reportMessage("Type was updated.");
                    };
                };

                $this->view->title = "View and Edit type [".(Principio_Common::$is_error ? $model_type_old->getCaption() : $this->view->model_type->getCaption())."]";
                $this->setActionViewData(self::ACTION_EDIT);
            };
        }
    

	
        public function customizeAction()
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "Type ID")))
            {
                $this->view->model_type = Principio_Model_TypeMapper::fetch($this->post_data["id"]);
                $this->view->action = "customize";

                if ($this->is_apply)
                {
                    for ($i = 0; $i <= $this->view->model_type->getExts() + 1; $i++)
                    {
                        if (!isset($this->post_data["ext".$i."_template"]))
                            $this->view->model_type->setTemplate($i - Principio_Model_Templatable::TEMPLATE_SHIFT, "");
                        else
                            $this->view->model_type->setTemplate($i - Principio_Model_Templatable::TEMPLATE_SHIFT, $this->post_data["ext".$i."_template"]);
                    };

                    if ($this->view->model_type->saveTemplates())
                        Principio_Common::reportMessage("Templates were updated.");
                };

                $this->setActionViewData(self::ACTION_CUSTOMIZE);
            };
        }

	
        public function addAction()
	    {
            if ($this->is_post)
            {
                $this->view->title = "Adding new type";
		        $this->view->action = "add";
                $this->view->is_add = true;
                $this->view->firmwares = Principio_Model_FirmwareMapper::get();
                $this->setActionViewData(self::ACTION_ADD);

                if ($this->is_apply)
		        {
                    if ($this->checkPostItemInt("exts", "Ext count"))
                    {
                        $this->view->model_type = new Principio_Model_Type(intval($this->post_data['exts']));

                        if ($this->validate())
                        {
                            if ($this->view->model_type->add())
                            {
                                Principio_Common::reportMessage("Type was added.");
                                $this->view->is_add = false;
                                $this->view->action = "view";
                                $this->view->title = "View and Edit type [".$this->view->model_type->getCaption()."]";
                                $this->setActionViewData(self::ACTION_EDIT);
                            };
                        };
                    }
                    else
                        $this->view->model_type = new Principio_Model_Type(0);
                }
                else
                    $this->view->model_type = new Principio_Model_Type(0);

            };
	    }


        public function tftpAction()
        {
            if (($this->is_post) && ($this->checkPostItemInt("id", "Type ID")))
            {
                $this->view->action = "tftp";
                $this->view->model_setting_profile_rule_FTP = Principio_Model_SettingMapper::getProfileRuleHTTP();
                $this->view->model_type = Principio_Model_TypeMapper::fetch($this->post_data['id']);

                if ($this->is_apply)
                {
                    if ( ($this->checkPostItemInt("tftp_use_default_config", "Use default TFTP config")) &&
                            Principio_Common::checkValidity(($this->post_data['tftp_use_default_config'] == 1) || ($this->post_data['tftp_use_default_config'] == 2), "Wrong value of [Use default TFTP config]"))
                    {
                        $this->view->model_type->setUseDefaultTFTPConfig($this->post_data['tftp_use_default_config'] - 1);

                        if ($this->view->model_type->getUseDefaultTFTPConfig() == 0)
                        {

                            if ($this->checkPostItem("tftp_custom_config"))
                                $this->view->model_type->setTFTPConfig($this->post_data['tftp_custom_config']);
                        }
                        else
                            $this->view->model_type->setDefaultTFTPConfig();
                    };

                    if ( ($this->checkPostItemInt("tftp_add_extra_config", "Add extra TFTP config")) &&
                        Principio_Common::checkValidity(($this->post_data['tftp_add_extra_config'] == 1) || ($this->post_data['tftp_add_extra_config'] == 2), "Wrong value of [Add extra TFTP config]"))
                    {
                        $this->view->model_type->setAddExtraTFTPConfig($this->post_data['tftp_add_extra_config'] - 1);

                        if ($this->view->model_type->getAddExtraTFTPConfig() == 1)
                        {
                            if ($this->checkPostItem("tftp_extra_config"))
                                $this->view->model_type->setExtraTFTPConfig($this->post_data['tftp_extra_config']);
                        }
                        else
                            $this->view->model_type->setExtraTFTPConfig("");
                    };

                    if ((!Principio_Common::$is_error) &&
                        (Principio_Model_TypeMapper::save($this->view->model_type) !== false))
                    {
                        Principio_Common::reportMessage("TFTP settings were saved.");
                    };
                };

                $this->setActionViewData(self::ACTION_TFTP);
            };
        }



        public function tftpdefaultconfigAction()
        {
            if ($this->is_post)
            {
                $this->view->model_setting_tftp_default_config = Principio_Model_SettingMapper::fetch(Principio_Model_SettingMapper::SETTING_TFTP_DEFAULT_CONFIG);
            };
        }



        public function deleteAction()
        {
            if ($this->is_post)
            {
                if ($this->checkPostItemInt("id", "Type ID"))
                {
                    if (Principio_Model_TypeMapper::fetch($this->post_data['id'])->delete())
                    {
                        Principio_DHCP::generate();
                        Principio_Common::reportMessage("Type was deleted.");
                    };
                };
            };
        }
}